<template>
  <view class="min-h-screen w-full max-w-[750rpx] bg-[#e0e0e0] mx-auto pb-[120rpx]">
    <backView :back="goBack"/>

    <!-- 页面标题 -->
    <view class="bg-[#27c530] text-white p-[30rpx] rounded-b-[20rpx]">
      <text class="text-[32rpx] font-bold text-center block">{{ now ? "电子病历" : "既往病史详情" }}</text>
    </view>

    <view class="p-[24rpx] pb-[120rpx]">
      <!-- 基本信息 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('basicInfo')">
          <text class="text-[28rpx] font-bold text-gray-800">基本信息</text>
          <IconFont
            :name="collapseStates.basicInfo ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.basicInfo ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.basicInfo" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <view class="flex items-center">
            <text class="text-[24rpx] text-gray-700 w-[150rpx]">姓名:</text>
            <nut-input :model-value="formData.name" @update:model-value="updateField('name', $event)" placeholder="请输入姓名" class="flex-1" />
          </view>
          <view class="flex items-center">
            <text class="text-[24rpx] text-gray-700 w-[150rpx]">证件号:</text>
            <nut-input :model-value="formData.idNumber" @update:model-value="updateField('idNumber', $event)" placeholder="请输入证件号码" class="flex-1" />
          </view>
          <view class="flex items-center">
            <text class="text-[24rpx] text-gray-700 w-[150rpx]">就诊时间:</text>
            <view 
              class="flex-1 border border-gray-200 rounded-lg p-3 flex items-center justify-between bg-white"
              @click="showCalendarPopup = true"
            >
              <text class="text-[24rpx]" :class="formData.visitTime ? 'text-gray-800' : 'text-gray-400'">
                {{ formData.visitTime ? formatVisitTime(visitTimeValue) : '请选择就诊时间' }}
              </text>
              <text class="text-[24rpx] text-gray-400">▼</text>
            </view>
          </view>
        </view>
      </view>

      

      <!-- 就诊机构 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('medicalInstitution')">
          <text class="text-[28rpx] font-bold text-gray-800">就诊机构</text>
          <IconFont
            :name="collapseStates.medicalInstitution ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.medicalInstitution ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.medicalInstitution" class="p-[24rpx] transition-all duration-300">
          <HospitalDepartmentProjectSelector 
            v-model="hospitalSelectorData"
            placeholder="请选择医院/部门/科室/项目组"
            @confirm="handleHospitalConfirm"
          />
          
          <!-- 显示已选择的信息 -->
          <view v-if="formData.hospital || formData.department || formData.dept || formData.project" class="mt-[24rpx] p-[20rpx] bg-blue-50 rounded-[12rpx]">
            <text class="block text-[24rpx] font-bold text-gray-700 mb-[12rpx]">已选择:</text>
            <view class="space-y-[8rpx]">
              <view v-if="formData.hospital" class="flex items-center">
                <text class="text-[22rpx] text-gray-600 w-[120rpx]">医院:</text>
                <text class="text-[22rpx] text-blue-600 flex-1">{{ formData.hospital }}</text>
              </view>
              <view v-if="formData.department" class="flex items-center">
                <text class="text-[22rpx] text-gray-600 w-[120rpx]">部门:</text>
                <text class="text-[22rpx] text-blue-600 flex-1">{{ formData.department }}</text>
              </view>
              <view v-if="formData.dept" class="flex items-center">
                <text class="text-[22rpx] text-gray-600 w-[120rpx]">科室:</text>
                <text class="text-[22rpx] text-blue-600 flex-1">{{ formData.dept }}</text>
              </view>
              <view v-if="formData.project" class="flex items-center">
                <text class="text-[22rpx] text-gray-600 w-[120rpx]">项目组:</text>
                <text class="text-[22rpx] text-blue-600 flex-1">{{ formData.project }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 主诉 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('chiefComplaint')">
          <text class="text-[28rpx] font-bold text-gray-800">主诉</text>
          <IconFont
            :name="collapseStates.chiefComplaint ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.chiefComplaint ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.chiefComplaint" class="p-[24rpx] transition-all duration-300">
          <ItemWithImagesCard
            :model-value="{ title: '', description: formData.chiefComplaint || '', images: formData.chiefComplaintImages || [] }"
            @update:model-value="(data) => { updateField('chiefComplaint', data.description); if (data.images?.length) updateField('chiefComplaintImages', data.images); }"
            :show-title="false"
            description-label="主诉症状"
            description-placeholder="请输入主诉症状和体征"
            :description-rows="3"
            border-color="border-purple-300"
          />
        </view>
      </view>


      <!-- 全面健康评估 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[48rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @doubleclick="toggleCollapse('healthAssessment')">
          <text class="text-[28rpx] font-bold text-gray-800">全面健康评估</text>
          <IconFont
            v-show="false"
            :name="collapseStates.healthAssessment ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.healthAssessment ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="true || collapseStates.healthAssessment" class="p-[24rpx] transition-all duration-300">
          <text class="text-[24rpx] text-gray-600 block mb-[30rpx]">进行详细的健康评估，包括体格检查、生理功能、风险评估等</text>
          <nut-button type="danger" class="!rounded-[12rpx] mb-[24rpx]" shape="square" size="large" block @click="goToHealthAssessment">
            <template #icon>
              <IconFont font-class-name="iconfont" class-prefix="icon" name="-yiliao" size="16" color="#fff" />
            </template>
            开始全面健康评估
          </nut-button>
        </view>
      </view>

      <!-- 专科评估 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('specialistAssessment')">
          <text class="text-[28rpx] font-bold text-gray-800">专科评估</text>
          <IconFont
            :name="collapseStates.specialistAssessment ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.specialistAssessment ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.specialistAssessment" class="p-[24rpx] transition-all duration-300">
          <ItemWithImagesCard
            :model-value="{ title: '', description: formData.specialistAssessment || '', images: formData.specialistAssessmentImages || [] }"
            @update:model-value="(data) => { updateField('specialistAssessment', data.description); if (data.images?.length) updateField('specialistAssessmentImages', data.images); }"
            :show-title="false"
            description-label="专科评估"
            description-placeholder="请输入专科评估内容"
            :description-rows="4"
            border-color="border-indigo-300"
          />
        </view>
      </view>

      <!-- 居家护理专项评估 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="goToHomeCareAssessment">
          <text class="text-[28rpx] font-bold text-gray-800">居家护理专项评估</text>
          <!-- <IconFont
            name="rect-right"
            size="16"
            color="#8bc34a"
          /> -->
        </view>
        <view class="p-[24rpx] transition-all duration-300">
          <text class="text-[24rpx] text-gray-600 block mb-[30rpx]">进行详细的居家护理专项评估，包括服务对象、监护人、服务人员三个视角的评估内容</text>
          <nut-button type="warning" class="!rounded-[12rpx] mb-[24rpx]" shape="square" size="large" block @click="goToHomeCareAssessment">
            <template #icon>
              <IconFont font-class-name="iconfont" class-prefix="icon" name="-yiliao" size="16" color="#fff" />
            </template>
            开始居家护理专项评估
          </nut-button>
        </view>
      </view>

      <!-- 诊断信息 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('diagnosisInfo')">
          <text class="text-[28rpx] font-bold text-gray-800">诊断结果及其依据</text>
          <IconFont
            :name="collapseStates.diagnosisInfo ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.diagnosisInfo ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.diagnosisInfo" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 疾病名称输入框 -->
          <view class="flex items-center">
            <text class="text-[24rpx] text-gray-700 w-[150rpx]">疾病名称:</text>
            <nut-input 
              :model-value="formData.diseaseName" 
              @update:model-value="updateField('diseaseName', $event)" 
              placeholder="请输入疾病名称" 
              class="flex-1" 
            />
          </view>
          
          <!-- 诊断项目列表 -->
          <view v-for="(item, index) in formData.diagnosisItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">诊断项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.diagnosisItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeDiagnosisItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <!-- 疾病名称 -->
            <view class="flex items-center mb-[12rpx]">
              <text class="text-[24rpx] text-gray-700 w-[150rpx]">疾病名称:</text>
              <nut-input 
                :model-value="item.diseaseName" 
                @update:model-value="updateDiagnosisItem(index, 'diseaseName', $event)" 
                placeholder="请输入疾病名称" 
                class="flex-1" 
              />
            </view>
            
            <!-- 诊断结果 -->
            <ItemWithImagesCard
              :model-value="{ title: '', description: item.diagnosisResult || '', images: item.diagnosisResultImages || [] }"
              @update:model-value="(data) => { 
                updateDiagnosisItem(index, 'diagnosisResult', data.description); 
                if (data.images?.length) updateDiagnosisItem(index, 'diagnosisResultImages', data.images); 
              }"
              :show-title="false"
              description-label="诊断结果"
              description-placeholder="请输入诊断结果"
              :description-rows="2"
              border-color="border-green-300"
            />
            
            <!-- 诊断依据 -->
            <ItemWithImagesCard
              :model-value="{ title: '', description: item.diagnosisBasis || '', images: item.diagnosisBasisImages || [] }"
              @update:model-value="(data) => { 
                updateDiagnosisItem(index, 'diagnosisBasis', data.description); 
                if (data.images?.length) updateDiagnosisItem(index, 'diagnosisBasisImages', data.images); 
              }"
              :show-title="false"
              description-label="诊断依据"
              description-placeholder="请输入诊断依据"
              :description-rows="2"
              border-color="border-teal-300"
            />
          </view>
          
          <!-- 添加新项目按钮 -->
          <view class="flex justify-center mt-[16rpx]">
            <nut-button type="primary" @click="addDiagnosisItem" class="px-[32rpx]">
              添加新项目
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 健康需求属性优化评估 -->
      <view class="youhua bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('healthDemandAttributeOptimization')">
          <text class="text-[28rpx] font-bold text-gray-800">健康需求属性优化评估</text>
          <IconFont
            :name="collapseStates.healthDemandAttributeOptimization ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.healthDemandAttributeOptimization ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.healthDemandAttributeOptimization" class="p-[24rpx] space-y-[20rpx] transition-all duration-300">
          <text class="text-[26rpx] font-bold text-gray-800 block mb-[16rpx]">健康评估核心四大属性</text>
          
          <!-- 医疗属性 -->
          <view class="bg-blue-50 rounded-[12rpx] p-[16rpx] space-y-[12rpx]">
            <view class="flex items-center justify-between">
              <text class="text-[26rpx] font-bold text-blue-600">1. 医疗属性</text>
              <view class="flex items-center space-x-[6rpx]">
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">占比:</text>
                <nut-input 
                  :model-value="formData.healthDemandAttributeOptimization?.medicalAttribute?.proportion?.toString() || '0'"
                  @update:model-value="updateHealthAttributeProportion('medicalAttribute', $event)"
                  type="number"
                  placeholder="0"
                  class="perct w-[50rpx] text-center !p-[4rpx] !text-[18rpx] !bg-white !border-green-200 !h-[32rpx] !min-h-[32rpx]"
                />
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">%</text>
              </view>
            </view>
            <ItemWithImagesCard
              :model-value="{ 
                title: '', 
                description: formData.healthDemandAttributeOptimization?.medicalAttribute?.description || '', 
                images: formData.healthDemandAttributeOptimization?.medicalAttribute?.images || [] 
              }"
              @update:model-value="(data) => updateHealthAttributeData('medicalAttribute', data)"
              :show-title="false"
              description-label="医疗属性描述"
              description-placeholder="请输入医疗属性相关描述"
              :description-rows="2"
              border-color="border-blue-300"
            />
          </view>

          <!-- 健康属性 -->
          <view class="bg-green-50 rounded-[12rpx] p-[16rpx] space-y-[12rpx]">
            <view class="flex items-center justify-between">
              <text class="text-[26rpx] font-bold text-green-600">2. 健康属性</text>
              <view class="flex items-center space-x-[6rpx]">
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">占比:</text>
                <nut-input 
                  :model-value="formData.healthDemandAttributeOptimization?.healthAttribute?.proportion?.toString() || '0'"
                  @update:model-value="updateHealthAttributeProportion('healthAttribute', $event)"
                  type="number"
                  placeholder="0"
                  class="perct w-[50rpx] text-center !p-[4rpx] !text-[18rpx] !bg-white !border-green-200 !h-[32rpx] !min-h-[32rpx]"
                />
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">%</text>
              </view>
            </view>
            <ItemWithImagesCard
              :model-value="{ 
                title: '', 
                description: formData.healthDemandAttributeOptimization?.healthAttribute?.description || '', 
                images: formData.healthDemandAttributeOptimization?.healthAttribute?.images || [] 
              }"
              @update:model-value="(data) => updateHealthAttributeData('healthAttribute', data)"
              :show-title="false"
              description-label="健康属性描述"
              description-placeholder="请输入健康属性相关描述"
              :description-rows="2"
              border-color="border-green-300"
            />
          </view>

          <!-- 康复属性 -->
          <view class="bg-orange-50 rounded-[12rpx] p-[16rpx] space-y-[12rpx]">
            <view class="flex items-center justify-between">
              <text class="text-[26rpx] font-bold text-orange-600">3. 康复属性</text>
              <view class="flex items-center space-x-[6rpx]">
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">占比:</text>
                <nut-input 
                  :model-value="formData.healthDemandAttributeOptimization?.rehabilitationAttribute?.proportion?.toString() || '0'"
                  @update:model-value="updateHealthAttributeProportion('rehabilitationAttribute', $event)"
                  type="number"
                  placeholder="0"
                  class="perct w-[50rpx] text-center !p-[4rpx] !text-[18rpx] !bg-white !border-orange-200 !h-[32rpx] !min-h-[32rpx]"
                />
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">%</text>
              </view>
            </view>
            <ItemWithImagesCard
              :model-value="{ 
                title: '', 
                description: formData.healthDemandAttributeOptimization?.rehabilitationAttribute?.description || '', 
                images: formData.healthDemandAttributeOptimization?.rehabilitationAttribute?.images || [] 
              }"
              @update:model-value="(data) => updateHealthAttributeData('rehabilitationAttribute', data)"
              :show-title="false"
              description-label="康复属性描述"
              description-placeholder="请输入康复属性相关描述"
              :description-rows="2"
              border-color="border-orange-300"
            />
          </view>

          <!-- 照护属性 -->
          <view class="bg-purple-50 rounded-[12rpx] p-[16rpx] space-y-[12rpx]">
            <view class="flex items-center justify-between">
              <text class="text-[26rpx] font-bold text-purple-600">4. 照护属性</text>
              <view class="flex items-center space-x-[6rpx]">
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">占比:</text>
                <nut-input 
                  :model-value="formData.healthDemandAttributeOptimization?.careAttribute?.proportion?.toString() || '0'"
                  @update:model-value="updateHealthAttributeProportion('careAttribute', $event)"
                  type="number"
                  placeholder="0"
                  class="perct w-[50rpx] text-center !p-[4rpx] !text-[18rpx] !bg-white !border-purple-200 !h-[32rpx] !min-h-[32rpx]"
                />
                <text class="text-[22rpx] text-gray-600 whitespace-nowrap">%</text>
              </view>
            </view>
            <ItemWithImagesCard
              :model-value="{ 
                title: '', 
                description: formData.healthDemandAttributeOptimization?.careAttribute?.description || '', 
                images: formData.healthDemandAttributeOptimization?.careAttribute?.images || [] 
              }"
              @update:model-value="(data) => updateHealthAttributeData('careAttribute', data)"
              :show-title="false"
              description-label="照护属性描述"
              description-placeholder="请输入照护属性相关描述"
              :description-rows="2"
              border-color="border-purple-300"
            />
          </view>

          <!-- 增加+按钮 -->
          <view class="flex justify-center mt-[8rpx]">
            <nut-button 
              type="primary" 
              size="small" 
              @click="addAdditionalAttribute"
              class="!rounded-[12rpx] !bg-gradient-to-r !from-blue-500 !to-purple-500 !border-none"
            >
              <template #icon>
                <IconFont name="plus" size="14" color="#fff" />
              </template>
              增加+...占比 %
            </nut-button>
          </view>

          <!-- 额外属性列表 -->
          <view v-if="formData.healthDemandAttributeOptimization?.additionalAttributes?.length" class="space-y-[16rpx] mt-[16rpx]">
            <view 
              v-for="(attr, index) in formData.healthDemandAttributeOptimization.additionalAttributes" 
              :key="index"
              class="space-y-[12rpx] border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx] bg-gray-50"
            >
              <view class="flex items-center justify-between">
                <nut-input 
                  :model-value="attr.name"
                  @update:model-value="updateAdditionalAttributeName(index, $event)"
                  placeholder="属性名称"
                  class="flex-1 mr-[12rpx]"
                />
                <view class="flex items-center space-x-[6rpx]">
                  <text class="text-[22rpx] text-gray-600 whitespace-nowrap">占比:</text>
                  <nut-input 
                    :model-value="attr.proportion.toString()"
                    @update:model-value="updateAdditionalAttributeProportion(index, $event)"
                    type="number"
                    placeholder="0"
                    class="w-[50rpx] text-center !p-[4rpx] !text-[16rpx] !h-[28rpx] !min-h-[28rpx]"
                  />
                  <text class="text-[22rpx] text-gray-600 whitespace-nowrap">%</text>
                </view>
                <nut-button 
                  type="danger" 
                  size="small" 
                  @click="removeAdditionalAttribute(index)"
                  class="!rounded-[8rpx] ml-[8rpx]"
                >
                  <template #icon>
                    <IconFont name="del" size="12" color="#fff" />
                  </template>
                </nut-button>
              </view>
              <ItemWithImagesCard
                :model-value="{ 
                  title: '', 
                  description: attr.description || '', 
                  images: attr.images || [] 
                }"
                @update:model-value="(data) => updateAdditionalAttributeData(index, data)"
                :show-title="false"
                description-label="属性描述"
                description-placeholder="请输入属性相关描述"
                :description-rows="2"
                border-color="border-gray-300"
              />
            </view>
          </view>

          <!-- 健康评估归档 -->
          <view class="mt-[24rpx] p-[16rpx] bg-gradient-to-r from-gray-50 to-blue-50 rounded-[12rpx] border border-gray-200">
            <text class="text-[24rpx] font-bold text-gray-700 block mb-[12rpx]">📋 健康评估归档处，以时间轴由近及远排序</text>
            <view v-if="formData.healthDemandAttributeOptimization?.historicalAssessments?.length" class="space-y-[8rpx]">
              <view 
                v-for="(assessment, index) in formData.healthDemandAttributeOptimization.historicalAssessments" 
                :key="index"
                class="flex items-center justify-between p-[12rpx] bg-white rounded-[8rpx] border border-gray-200"
              >
                <text class="text-[22rpx] text-gray-600">{{ assessment.date }}</text>
                <text class="text-[22rpx] text-gray-800 flex-1 ml-[12rpx]">{{ assessment.assessment }}</text>
                <nut-button 
                  type="danger" 
                  size="mini" 
                  @click="removeHistoricalAssessment(index)"
                  class="!rounded-[6rpx]"
                >
                  <template #icon>
                    <IconFont name="del" size="10" color="#fff" />
                  </template>
                </nut-button>
              </view>
            </view>
            <view v-else class="text-center py-[20rpx]">
              <text class="text-[22rpx] text-gray-500">暂无历史评估记录</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 治疗计划 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('treatmentPlan')">
          <text class="text-[28rpx] font-bold text-gray-800">治疗计划与方案</text>
          <IconFont
            :name="collapseStates.treatmentPlan ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.treatmentPlan ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.treatmentPlan" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 用药记录列表 -->
          <view v-for="(medication, index) in formData.medicationRecords" :key="index" class="bg-gray-50 rounded-[12rpx] p-[20rpx] border border-gray-200 mb-[16rpx]">
            <view class="flex items-center justify-between mb-[16rpx]">
              <text class="text-[26rpx] font-bold text-gray-700">用药记录</text>
              <view class="flex items-center space-x-[12rpx]">
                <view class="px-[12rpx] py-[6rpx] bg-blue-100 rounded-[8rpx]">
                  <text class="text-[20rpx] text-blue-600 font-medium">记录 {{ index + 1 }}</text>
                </view>
                <view @click="removeMedicationRecord(index)" class="w-[32rpx] h-[32rpx] flex items-center justify-center">
                  <IconFont name="close" size="14" color="#ef4444" />
                </view>
              </view>
            </view>
            
            <view class="grid grid-cols-1 gap-[16rpx]">
              <!-- 药物名称 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">药物名称</text>
                <nut-input 
                  v-model="medication.drugName" 
                  placeholder="请输入药物名称"
                  class="w-full"
                />
              </view>
              
              <!-- 用药方法 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">用药方法</text>
                <nut-input 
                  v-model="medication.medicationMethod" 
                  placeholder="请输入用药方法（如：口服、注射等）"
                  class="w-full"
                />
              </view>
              
              <!-- 用药剂量 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">用药剂量</text>
                <nut-input 
                  v-model="medication.dosage" 
                  placeholder="请输入用药剂量"
                  class="w-full"
                />
              </view>
              
              <!-- 用药频率 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">用药频率</text>
                <nut-input 
                  v-model="medication.medicationFrequency" 
                  placeholder="请输入用药频率"
                  class="w-full"
                />
              </view>
              
              <!-- 用药时长 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">用药时长</text>
                <nut-input 
                  v-model="medication.medicationTime" 
                  placeholder="请输入用药时长"
                  class="w-full"
                />
              </view>
              
              <!-- 用药效果 -->
              <view class="bg-white rounded-[8rpx] p-[16rpx] border border-gray-200">
                <text class="text-[22rpx] font-medium text-gray-600 mb-[8rpx] block">用药效果</text>
                <nut-textarea 
                  v-model="medication.effect" 
                  placeholder="请输入用药效果"
                  :rows="3"
                  class="w-full"
                />
              </view>
            </view>
          </view>
          
          <!-- 添加用药记录按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-green-300 active:bg-green-50" @click="addMedicationRecord">
            <IconFont name="plus" size="24" color="#00b26a" />
            <text class="text-[24rpx] text-[#00b26a] ml-[8rpx]">添加用药记录</text>
          </view>
          
          <!-- 处置项目列表 -->
          <view v-for="(item, index) in formData.dispositionItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">处置项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.dispositionItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeDispositionItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updateDispositionItem(index, data)"
              :show-title="true"
              title-label="处置标题"
              title-placeholder="请输入处置标题"
              description-label="处置内容"
              description-placeholder="请输入处置方案"
              :description-rows="2"
              border-color="border-green-300"
            />
          </view>
          
          <!-- 添加处置项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-green-300 active:bg-green-50" @click="addDispositionItem">
            <IconFont name="plus" size="24" color="#00b26a" />
            <text class="text-[24rpx] text-[#00b26a] ml-[8rpx]">添加处置项目</text>
          </view>
          
          <!-- 健康教育项目列表 -->
          <view v-for="(item, index) in formData.healthEducationItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">健康教育项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.healthEducationItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeHealthEducationItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updateHealthEducationItem(index, data)"
              :show-title="true"
              title-label="健康教育标题"
              title-placeholder="请输入健康教育标题"
              description-label="健康教育内容"
              description-placeholder="请输入健康教育内容"
              :description-rows="2"
              border-color="border-purple-300"
            />
          </view>
          
          <!-- 添加健康教育项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-green-300 active:bg-green-50" @click="addHealthEducationItem">
            <IconFont name="plus" size="24" color="#00b26a" />
            <text class="text-[24rpx] text-[#00b26a] ml-[8rpx]">添加健康教育项目</text>
          </view>
        </view>
      </view>

      <!-- 手术计划 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('surgeryHistory')">
          <text class="text-[28rpx] font-bold text-gray-800">手术计划</text>
          <IconFont
            :name="collapseStates.surgeryHistory ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.surgeryHistory ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.surgeryHistory" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 手术史项目列表 -->
          <view v-for="(item, index) in formData.surgeryItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">手术史项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.surgeryItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeSurgeryItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updateSurgeryItem(index, data)"
              :show-title="true"
              title-label="手术标题"
              title-placeholder="请输入手术标题"
              description-label="手术详情"
              description-placeholder="请输入手术详情"
              :description-rows="2"
              border-color="border-orange-300"
            />
          </view>
          
          <!-- 添加手术史项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-orange-300 active:bg-orange-50" @click="addSurgeryItem">
            <IconFont name="plus" size="24" color="#ff9800" />
            <text class="text-[24rpx] text-[#ff9800] ml-[8rpx]">添加手术史项目</text>
          </view>
        </view>
      </view>

      <!-- 过敏防治 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('allergyHistory')">
          <text class="text-[28rpx] font-bold text-gray-800">过敏防治</text>
          <IconFont
            :name="collapseStates.allergyHistory ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.allergyHistory ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.allergyHistory" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 过敏史项目列表 -->
          <view v-for="(item, index) in formData.allergyItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">过敏史项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.allergyItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeAllergyItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updateAllergyItem(index, data)"
              :show-title="true"
              title-label="过敏类型"
              title-placeholder="请输入过敏类型"
              description-label="过敏详情"
              description-placeholder="请输入过敏详情"
              :description-rows="2"
              border-color="border-red-300"
            />
          </view>
          
          <!-- 添加过敏史项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-red-300 active:bg-red-50" @click="addAllergyItem">
            <IconFont name="plus" size="24" color="#f44336" />
            <text class="text-[24rpx] text-[#f44336] ml-[8rpx]">添加过敏史项目</text>
          </view>
        </view>
      </view>

      <!-- 预防接种与筛查计划 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('vaccinationScreening')">
          <text class="text-[28rpx] font-bold text-gray-800">预防接种与筛查计划</text>
          <IconFont
            :name="collapseStates.vaccinationScreening ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.vaccinationScreening ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.vaccinationScreening" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 接种项目列表 -->
          <view class="border border-blue-200 rounded-[12rpx] p-[16rpx] bg-blue-50">
            <text class="text-[24rpx] font-semibold text-blue-800 block mb-[12rpx]">💉 接种</text>
            
            <view v-for="(item, index) in formData.vaccinationItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
              <view class="flex items-center justify-between mb-[12rpx]">
                <text class="text-[24rpx] font-medium text-gray-700">接种项目 {{ index + 1 }}</text>
                <nut-button 
                  v-if="formData.vaccinationItems.length > 1"
                  type="danger" 
                  size="small" 
                  @click="removeVaccinationItem(index)"
                >
                  删除
                </nut-button>
              </view>
              
              <ItemWithImagesCard
                :model-value="item"
                @update:model-value="(data) => updateVaccinationItem(index, data)"
                :show-title="true"
                title-label="疫苗名称"
                title-placeholder="请输入疫苗名称"
                description-label="接种详情"
                description-placeholder="请输入接种详情"
                :description-rows="2"
                border-color="border-blue-300"
              />
            </view>
            
            <!-- 添加接种项目按钮 -->
            <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-blue-300 active:bg-blue-50" @click="addVaccinationItem">
              <IconFont name="plus" size="24" color="#2196f3" />
              <text class="text-[24rpx] text-[#2196f3] ml-[8rpx]">添加接种项目</text>
            </view>
          </view>

          <!-- 筛查项目列表 -->
          <view class="border border-green-200 rounded-[12rpx] p-[16rpx] bg-green-50">
            <text class="text-[24rpx] font-semibold text-green-800 block mb-[12rpx]">🔍 筛查</text>
            
            <view v-for="(item, index) in formData.screeningItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
              <view class="flex items-center justify-between mb-[12rpx]">
                <text class="text-[24rpx] font-medium text-gray-700">筛查项目 {{ index + 1 }}</text>
                <nut-button 
                  v-if="formData.screeningItems.length > 1"
                  type="danger" 
                  size="small" 
                  @click="removeScreeningItem(index)"
                >
                  删除
                </nut-button>
              </view>
              
              <ItemWithImagesCard
                :model-value="item"
                @update:model-value="(data) => updateScreeningItem(index, data)"
                :show-title="true"
                title-label="筛查类型"
                title-placeholder="请输入筛查类型"
                description-label="筛查详情"
                description-placeholder="请输入筛查详情"
                :description-rows="2"
                border-color="border-green-300"
              />
            </view>
            
            <!-- 添加筛查项目按钮 -->
            <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-green-300 active:bg-green-50" @click="addScreeningItem">
              <IconFont name="plus" size="24" color="#4caf50" />
              <text class="text-[24rpx] text-[#4caf50] ml-[8rpx]">添加筛查项目</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 周期性健康检查计划 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('periodicHealthCheck')">
          <text class="text-[28rpx] font-bold text-gray-800">周期性健康检查计划</text>
          <IconFont
            :name="collapseStates.periodicHealthCheck ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.periodicHealthCheck ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.periodicHealthCheck" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 周期性健康检查项目列表 -->
          <view v-for="(item, index) in formData.periodicHealthCheckItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">健康检查项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.periodicHealthCheckItems.length > 1"
                type="danger" 
                size="small" 
                @click="removePeriodicHealthCheckItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updatePeriodicHealthCheckItem(index, data)"
              :show-title="true"
              title-label="检查类型"
              title-placeholder="请输入检查类型"
              description-label="检查详情"
              description-placeholder="请输入检查详情"
              :description-rows="2"
              border-color="border-blue-300"
            />
          </view>
          
          <!-- 添加周期性健康检查项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-blue-300 active:bg-blue-50" @click="addPeriodicHealthCheckItem">
            <IconFont name="plus" size="24" color="#2196f3" />
            <text class="text-[24rpx] text-[#2196f3] ml-[8rpx]">添加健康检查项目</text>
          </view>
        </view>
      </view>

      <!-- 生活方式与习惯改善计划 -->
      <view class="bg-white rounded-[20rpx] shadow-md mb-[24rpx] overflow-hidden">
        <view class="bg-[#e4f0e4] p-[24rpx] btops border-b border-gray-100 flex items-center justify-between" @click="toggleCollapse('lifestyleImprovement')">
          <text class="text-[28rpx] font-bold text-gray-800">生活方式与习惯改善计划</text>
          <IconFont
            :name="collapseStates.lifestyleImprovement ? 'arrow-up' : 'arrow-down'"
            size="12"
            color="#8bc34a"
            :class="['transition-transform duration-200', collapseStates.lifestyleImprovement ? 'rotate-180' : 'rotate-0']"
          />
        </view>
        <view v-show="collapseStates.lifestyleImprovement" class="p-[24rpx] space-y-[16rpx] transition-all duration-300">
          <!-- 生活方式项目列表 -->
          <view v-for="(item, index) in formData.lifestyleItems" :key="index" class="border border-gray-200 rounded-[12rpx] p-[16rpx] mb-[16rpx]">
            <view class="flex items-center justify-between mb-[12rpx]">
              <text class="text-[24rpx] font-medium text-gray-700">生活方式项目 {{ index + 1 }}</text>
              <nut-button 
                v-if="formData.lifestyleItems.length > 1"
                type="danger" 
                size="small" 
                @click="removeLifestyleItem(index)"
              >
                删除
              </nut-button>
            </view>
            
            <ItemWithImagesCard
              :model-value="item"
              @update:model-value="(data) => updateLifestyleItem(index, data)"
              :show-title="true"
              title-label="生活方式类型"
              title-placeholder="请输入生活方式类型"
              description-label="生活方式详情"
              description-placeholder="请输入生活方式详情"
              :description-rows="2"
              border-color="border-orange-300"
            />
          </view>
          
          <!-- 添加生活方式项目按钮 -->
          <view class="flex items-center justify-center p-[24rpx] rounded-[12rpx] border-2 border-dashed border-orange-300 active:bg-orange-50" @click="addLifestyleItem">
            <IconFont name="plus" size="24" color="#ff9800" />
            <text class="text-[24rpx] text-[#ff9800] ml-[8rpx]">添加生活方式项目</text>
          </view>
        </view>
      </view>



      <!-- 操作按钮 -->
      <view class="flex-center gap-[16rpx] mt-[32rpx] w-full">
        <nut-button type="default" size="normal" class="flex-1" @click="goBack">取消</nut-button>
        <nut-button type="success" size="normal" class="flex-1" @click="submitForm">保存</nut-button>
        <nut-button type="primary" size="normal" class="flex-[1.64] btnss" v-if="pinggu" @click="changeHealthAssessmentStatus">转为入户工单</nut-button>
      </view>
    </view>

    <!-- 就诊时间日历弹窗 -->
    <nut-popup 
      v-model:visible="showCalendarPopup" 
      position="bottom" 
      :style="{ height: '70%' }"
      round
    >
      <view class="calendar-popup">
        <view class="popup-header">
          <text class="popup-title">选择就诊时间</text>
          <view class="close-btn" @click="showCalendarPopup = false">
            <text>✕</text>
          </view>
        </view>
        
        <view class="calendar-content">
          <nut-calendar-card v-model="visitTimeValue" @change="onVisitTimeChange"></nut-calendar-card>
        </view>
        
        <view class="popup-footer">
          <nut-button 
            type="default" 
            class="flex-1"
            @click="showCalendarPopup = false"
          >
            取消
          </nut-button>
          <nut-button 
            type="primary" 
            class="flex-1 ml-3"
            @click="confirmVisitTime"
          >
            确定
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref, computed } from "vue";
import Taro from "@tarojs/taro";
import { request } from "@/service/request";
import { localStg } from "@/utils";
import { PageItem } from "./fields";
import backView from "@/components/backView.vue";
import { useMedicalRecordStore } from "@/store/modules";
import { IconFont } from "@nutui/icons-vue-taro";
import HospitalDepartmentProjectSelector from "@/components/HospitalDepartmentProjectSelector.vue";
import ItemWithImagesCard from "@/components/ItemWithImagesCard.vue";

// 获取 store 实例
const medicalRecordStore = useMedicalRecordStore();

// HospitalDepartmentProjectSelector 数据
const hospitalSelectorData = ref({
  hospital: null,
  department: null,
  dept: null,
  project: null
});

// 记录ID，用于判断是新增还是编辑
const recordId = ref("");

// 折叠状态管理
const collapseStates = ref({
  basicInfo: false, // 基本信息
  diagnosisInfo: false, // 诊断信息
  medicalInstitution: false, // 就诊机构
  specialistAssessment: false, // 专科评估
  surgeryHistory: false, // 手术史
  allergyHistory: false, // 过敏史
  vaccinationScreening: false, // 预防接种与筛查计划
  periodicHealthCheck: false, // 周期性健康检查计划
  lifestyleImprovement: false, // 生活方式与习惯改善计划
  allergyPrevention: false, // 过敏防治
  treatmentPlan: false, // 治疗计划
  chiefComplaint: false, // 主诉
  healthAssessment: false, // 全面健康评估
  healthDemandAttributeOptimization: false, // 健康需求属性优化评估
});

// 切换折叠状态
const toggleCollapse = (section: keyof typeof collapseStates.value) => {
  collapseStates.value[section] = !collapseStates.value[section];
};

// 获取 store 中的 formData
const formData = computed(() => {
  const storeData = medicalRecordStore.getData;
  if (storeData) {
    return storeData;
  }
  // 如果没有数据，返回默认结构
  return medicalRecordStore.getDefaultFormData();
});

/**
 * 更新字段值
 */
function updateField(field: string, value: any) {
  console.log("更新字段:", field, value);
  medicalRecordStore.updateField(field as any, value);
}

/**
 * 更新诊断项目
 */
function updateDiagnosisItem(index: number, field: string, value: any) {
  console.log("更新诊断项目:", index, field, value);
  
  // 确保 diagnosisItems 数组存在
  if (!formData.value.diagnosisItems) {
    updateField('diagnosisItems', []);
  }
  
  // 创建新的数组，更新指定项目的字段
  const updatedItems = [...formData.value.diagnosisItems];
  updatedItems[index] = {
    ...updatedItems[index],
    [field]: value
  };
  
  updateField('diagnosisItems', updatedItems);
}

/**
 * 添加诊断项目
 */
function addDiagnosisItem() {
  console.log("添加诊断项目");
  
  // 确保 diagnosisItems 数组存在
  if (!formData.value.diagnosisItems) {
    updateField('diagnosisItems', []);
  }
  
  // 创建新的诊断项目
  const newDiagnosisItem = {
    diseaseName: "",
    diagnosisResult: "",
    diagnosisResultImages: [],
    diagnosisBasis: "",
    diagnosisBasisImages: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.diagnosisItems || [];
  const updatedItems = [...currentItems, newDiagnosisItem];
  updateField('diagnosisItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加诊断项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除诊断项目
 */
function removeDiagnosisItem(index: number) {
  console.log("删除诊断项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.diagnosisItems && formData.value.diagnosisItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个诊断项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.diagnosisItems.filter((_: any, i: number) => i !== index);
  updateField('diagnosisItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除诊断项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新处置项目
 */
function updateDispositionItem(index: number, data: any) {
  console.log("更新处置项目:", index, data);
  
  // 确保 dispositionItems 数组存在
  if (!formData.value.dispositionItems) {
    updateField('dispositionItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.dispositionItems];
  updatedItems[index] = data;
  
  updateField('dispositionItems', updatedItems);
}

/**
 * 添加处置项目
 */
function addDispositionItem() {
  console.log("添加处置项目");
  
  // 确保 dispositionItems 数组存在
  if (!formData.value.dispositionItems) {
    updateField('dispositionItems', []);
  }
  
  // 创建新的处置项目
  const newDispositionItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.dispositionItems || [];
  const updatedItems = [...currentItems, newDispositionItem];
  updateField('dispositionItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加处置项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除处置项目
 */
function removeDispositionItem(index: number) {
  console.log("删除处置项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.dispositionItems && formData.value.dispositionItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个处置项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.dispositionItems.filter((_: any, i: number) => i !== index);
  updateField('dispositionItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除处置项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新健康教育项目
 */
function updateHealthEducationItem(index: number, data: any) {
  console.log("更新健康教育项目:", index, data);
  
  // 确保 healthEducationItems 数组存在
  if (!formData.value.healthEducationItems) {
    updateField('healthEducationItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.healthEducationItems];
  updatedItems[index] = data;
  
  updateField('healthEducationItems', updatedItems);
}

/**
 * 添加健康教育项目
 */
function addHealthEducationItem() {
  console.log("添加健康教育项目");
  
  // 确保 healthEducationItems 数组存在
  if (!formData.value.healthEducationItems) {
    updateField('healthEducationItems', []);
  }
  
  // 创建新的健康教育项目
  const newHealthEducationItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.healthEducationItems || [];
  const updatedItems = [...currentItems, newHealthEducationItem];
  updateField('healthEducationItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加健康教育项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除健康教育项目
 */
function removeHealthEducationItem(index: number) {
  console.log("删除健康教育项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.healthEducationItems && formData.value.healthEducationItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个健康教育项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.healthEducationItems.filter((_: any, i: number) => i !== index);
  updateField('healthEducationItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除健康教育项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新手术史项目
 */
function updateSurgeryItem(index: number, data: any) {
  console.log("更新手术史项目:", index, data);
  
  // 确保 surgeryItems 数组存在
  if (!formData.value.surgeryItems) {
    updateField('surgeryItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.surgeryItems];
  updatedItems[index] = data;
  
  updateField('surgeryItems', updatedItems);
}

/**
 * 添加手术史项目
 */
function addSurgeryItem() {
  console.log("添加手术史项目");
  
  // 确保 surgeryItems 数组存在
  if (!formData.value.surgeryItems) {
    updateField('surgeryItems', []);
  }
  
  // 创建新的手术史项目
  const newSurgeryItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.surgeryItems || [];
  const updatedItems = [...currentItems, newSurgeryItem];
  updateField('surgeryItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加手术史项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除手术史项目
 */
function removeSurgeryItem(index: number) {
  console.log("删除手术史项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.surgeryItems && formData.value.surgeryItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个手术史项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.surgeryItems.filter((_: any, i: number) => i !== index);
  updateField('surgeryItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除手术史项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新过敏史项目
 */
function updateAllergyItem(index: number, data: any) {
  console.log("更新过敏史项目:", index, data);
  
  // 确保 allergyItems 数组存在
  if (!formData.value.allergyItems) {
    updateField('allergyItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.allergyItems];
  updatedItems[index] = data;
  
  updateField('allergyItems', updatedItems);
}

/**
 * 添加过敏史项目
 */
function addAllergyItem() {
  console.log("添加过敏史项目");
  
  // 确保 allergyItems 数组存在
  if (!formData.value.allergyItems) {
    updateField('allergyItems', []);
  }
  
  // 创建新的过敏史项目
  const newAllergyItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.allergyItems || [];
  const updatedItems = [...currentItems, newAllergyItem];
  updateField('allergyItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加过敏史项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除过敏史项目
 */
function removeAllergyItem(index: number) {
  console.log("删除过敏史项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.allergyItems && formData.value.allergyItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个过敏史项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.allergyItems.filter((_: any, i: number) => i !== index);
  updateField('allergyItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除过敏史项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新接种项目
 */
function updateVaccinationItem(index: number, data: any) {
  console.log("更新接种项目:", index, data);
  
  // 确保 vaccinationItems 数组存在
  if (!formData.value.vaccinationItems) {
    updateField('vaccinationItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.vaccinationItems];
  updatedItems[index] = data;
  
  updateField('vaccinationItems', updatedItems);
}

/**
 * 添加接种项目
 */
function addVaccinationItem() {
  console.log("添加接种项目");
  
  // 确保 vaccinationItems 数组存在
  if (!formData.value.vaccinationItems) {
    updateField('vaccinationItems', []);
  }
  
  // 创建新的接种项目
  const newVaccinationItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.vaccinationItems || [];
  const updatedItems = [...currentItems, newVaccinationItem];
  updateField('vaccinationItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加接种项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除接种项目
 */
function removeVaccinationItem(index: number) {
  console.log("删除接种项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.vaccinationItems && formData.value.vaccinationItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个接种项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.vaccinationItems.filter((_: any, i: number) => i !== index);
  updateField('vaccinationItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除接种项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新筛查项目
 */
function updateScreeningItem(index: number, data: any) {
  console.log("更新筛查项目:", index, data);
  
  // 确保 screeningItems 数组存在
  if (!formData.value.screeningItems) {
    updateField('screeningItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.screeningItems];
  updatedItems[index] = data;
  
  updateField('screeningItems', updatedItems);
}

/**
 * 添加筛查项目
 */
function addScreeningItem() {
  console.log("添加筛查项目");
  
  // 确保 screeningItems 数组存在
  if (!formData.value.screeningItems) {
    updateField('screeningItems', []);
  }
  
  // 创建新的筛查项目
  const newScreeningItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.screeningItems || [];
  const updatedItems = [...currentItems, newScreeningItem];
  updateField('screeningItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加筛查项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除筛查项目
 */
function removeScreeningItem(index: number) {
  console.log("删除筛查项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.screeningItems && formData.value.screeningItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个筛查项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.screeningItems.filter((_: any, i: number) => i !== index);
  updateField('screeningItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除筛查项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新周期性健康检查项目
 */
function updatePeriodicHealthCheckItem(index: number, data: any) {
  console.log("更新周期性健康检查项目:", index, data);
  
  // 确保 periodicHealthCheckItems 数组存在
  if (!formData.value.periodicHealthCheckItems) {
    updateField('periodicHealthCheckItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.periodicHealthCheckItems];
  updatedItems[index] = data;
  
  updateField('periodicHealthCheckItems', updatedItems);
}

/**
 * 添加周期性健康检查项目
 */
function addPeriodicHealthCheckItem() {
  console.log("添加周期性健康检查项目");
  
  // 确保 periodicHealthCheckItems 数组存在
  if (!formData.value.periodicHealthCheckItems) {
    updateField('periodicHealthCheckItems', []);
  }
  
  // 创建新的周期性健康检查项目
  const newPeriodicHealthCheckItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.periodicHealthCheckItems || [];
  const updatedItems = [...currentItems, newPeriodicHealthCheckItem];
  updateField('periodicHealthCheckItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加周期性健康检查项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除周期性健康检查项目
 */
function removePeriodicHealthCheckItem(index: number) {
  console.log("删除周期性健康检查项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.periodicHealthCheckItems && formData.value.periodicHealthCheckItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个周期性健康检查项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.periodicHealthCheckItems.filter((_: any, i: number) => i !== index);
  updateField('periodicHealthCheckItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除周期性健康检查项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 更新生活方式项目
 */
function updateLifestyleItem(index: number, data: any) {
  console.log("更新生活方式项目:", index, data);
  
  // 确保 lifestyleItems 数组存在
  if (!formData.value.lifestyleItems) {
    updateField('lifestyleItems', []);
  }
  
  // 创建新的数组，更新指定项目
  const updatedItems = [...formData.value.lifestyleItems];
  updatedItems[index] = data;
  
  updateField('lifestyleItems', updatedItems);
}

/**
 * 添加生活方式项目
 */
function addLifestyleItem() {
  console.log("添加生活方式项目");
  
  // 确保 lifestyleItems 数组存在
  if (!formData.value.lifestyleItems) {
    updateField('lifestyleItems', []);
  }
  
  // 创建新的生活方式项目
  const newLifestyleItem = {
    title: "",
    description: "",
    images: []
  };
  
  // 添加到数组中
  const currentItems = formData.value.lifestyleItems || [];
  const updatedItems = [...currentItems, newLifestyleItem];
  updateField('lifestyleItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加生活方式项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除生活方式项目
 */
function removeLifestyleItem(index: number) {
  console.log("删除生活方式项目:", index);
  
  // 确保至少保留一个项目
  if (formData.value.lifestyleItems && formData.value.lifestyleItems.length <= 1) {
    Taro.showToast({
      title: '至少需要保留一个生活方式项目',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  // 创建新的数组，移除指定项目
  const updatedItems = formData.value.lifestyleItems.filter((_: any, i: number) => i !== index);
  updateField('lifestyleItems', updatedItems);
  
  // 显示成功提示
  Taro.showToast({
    title: '删除生活方式项目成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 添加用药记录
 */
function addMedicationRecord() {
  console.log("添加用药记录");
  
  // 确保 medicationRecords 数组存在
  if (!formData.value.medicationRecords) {
    updateField('medicationRecords', []);
  }
  
  // 创建新的用药记录
  const newMedicationRecord = {
    drugName: '',           // 药物名称
    medicationMethod: '',   // 用药方法
    dosage: '',            // 用药剂量
    medicationFrequency: '', // 用药频率
    medicationTime: '',    // 用药时长
    effect: ''             // 用药效果
  };
  
  // 添加到数组中
  const currentRecords = formData.value.medicationRecords || [];
  const updatedRecords = [...currentRecords, newMedicationRecord];
  updateField('medicationRecords', updatedRecords);
  
  // 显示成功提示
  Taro.showToast({
    title: '添加用药记录成功',
    icon: 'success',
    duration: 1500
  });
}

/**
 * 删除用药记录
 */
function removeMedicationRecord(index: number) {
  console.log("删除用药记录", index);
  
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除这条用药记录吗？',
    success: (res) => {
      if (res.confirm) {
        const currentRecords = formData.value.medicationRecords || [];
        const updatedRecords = currentRecords.filter((_, i) => i !== index);
        updateField('medicationRecords', updatedRecords);
        
        Taro.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 1500
        });
      }
    }
  });
}

// 就诊时间输入框的值（datetime-local 格式）
// 控制日历弹窗显示
const showCalendarPopup = ref(false);

// 就诊时间日历值
const visitTimeValue = computed({
  get: () => {
    const visitTime = formData.value?.visitTime;
    if (!visitTime) return new Date();
    
    try {
      const date = new Date(visitTime);
      return isNaN(date.getTime()) ? new Date() : date;
    } catch (error) {
      console.error("解析就诊时间失败:", error);
      return new Date();
    }
  },
  set: (val: Date) => {
    if (val) {
      medicalRecordStore.updateField("visitTime", val.toISOString());
    }
  }
});

// 日历组件变化事件
const onVisitTimeChange = (val: Date) => {
  console.log("就诊时间变化:", val);
  if (val) {
    medicalRecordStore.updateField("visitTime", val.toISOString());
  }
};

// 确认选择就诊时间
const confirmVisitTime = () => {
  showCalendarPopup.value = false;
  console.log("确认就诊时间:", visitTimeValue.value);
};

// 格式化就诊时间显示
const formatVisitTime = (date: Date) => {
  if (!date) return '';
  
  try {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}年${month}月${day}日`;
  } catch (error) {
    console.error("格式化时间失败:", error);
    return '';
  }
};

// 表单数据，参考 getKillInfo 结构
const form = reactive({
  // 基本信息
  name: "",
  idNumber: "",
  seeDate: "",
  recordid: "",

  // 诊断信息
  chiefComplaint: "",
  diseaseName: "",
  diagnosisItems: [
    {
      diseaseName: "",
      diagnosisResult: "",
      diagnosisResultImages: [],
      diagnosisBasis: "",
      diagnosisBasisImages: []
    }
  ],

  // 就诊机构
  hospital: "",
  department: "",
  dept: "",
  project: "",

  // 专科评估
  specialistAssessment: "",

  // 手术史
  surgeryItems: [
    {
      title: "",
      description: "",
      images: []
    }
  ],

  // 过敏史
  allergyItems: [
    {
      title: "",
      description: "",
      images: []
    }
  ],

  // 家族病史
  familyDiseaseHistory: "",

  // 其他病史信息
  ifDisease: "",
  ifOpera: "",
  allergy: "",
  allergyDsc: "",
  ifFamDis: "",
  ifGeneticDis: "",
  geneticDisDsc: "",
  ifTrauma: "",
  ifInbloob: "",
  expose: "",
  disableDsc: "",

  // 体格检查
  physicalExamination: "",
  organExamination: "",
  auxiliaryExamination: "",

  // 治疗计划
  prescription: "",
  dispositionItems: [
    {
      title: "",
      description: "",
      images: []
    }
  ],
  healthEducationItems: [
    {
      title: "",
      description: "",
      images: []
    }
  ],

  // 备注
  note: "",
});

const now = ref(false);
const pinggu = ref(false);

// 处理医院选择器确认事件
const handleHospitalConfirm = (data: any) => {
  console.log('选择的医院数据:', data);
  
  // 更新表单数据
  if (data.hospital) {
    medicalRecordStore.updateField('hospital', data.hospital.title);
  }
  if (data.department) {
    medicalRecordStore.updateField('department', data.department.title);
  }
  // 科室信息
  if (data.dept) {
    medicalRecordStore.updateField('dept', data.dept.title);
  }
  // 项目组信息
  if (data.project) {
    medicalRecordStore.updateField('project', data.project.title);
  }
  
  console.log('更新后的表单数据:', formData.value);
  
  // 显示成功提示
  Taro.showToast({
    title: '选择成功',
    icon: 'success',
    duration: 1500
  });
};

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  pinggu.value = urlParams.get("pinggu") == "1";

  // 获取路由参数
  const params = Taro.getCurrentInstance().router?.params;
  console.log("路由参数:", params);

  now.value = !!params?.now;

  if (params?.id) {
    // 如果有ID参数，说明是查看/编辑模式
    recordId.value = params.id;
    console.log("编辑模式，记录ID:", recordId.value);

    // 加载现有数据
    await loadRecordData(params.id);
    return;
  }

  if (now.value) {
    await getCurRecord();
    return;
  }

  // 新增模式
  console.log("新增模式");
  initCurRecord();
});

function initCurRecord() {
  // 初始化 store 数据
  medicalRecordStore.initializeFormData();

  // 从本地存储获取用户基本信息
  const obj = localStg.get("demographicInfo");
  console.log("用户信息:", obj);

  if (obj) {
    // 更新 store 中的基本信息
    medicalRecordStore.updateField("name", obj.name || "");
    medicalRecordStore.updateField("idNumber", obj.idNumber || "");
    medicalRecordStore.updateField("recordid", obj.recordid || "");
  }

  // 设置默认就诊时间为当前时间
  const date = new Date();
  medicalRecordStore.updateField("visitTime", date.toISOString());
}

async function getCurRecord() {
  const obj = localStg.get("demographicInfo");
  const { success } = await request.get<any>(
    `${PageItem.commUrl}/list`,
    {
      idNumber: obj.idNumber,
      column: "createTime",
      order: "desc",
    },
    {
      useErrMsg: true,
    }
  );
  console.log("success cur record", success);
  if (success.records.length > 0) {
    initRecordData(success.records[0]);
  } else {
    initCurRecord();
  }

  // initRecordData(success);
}

function initRecordData(success: any) {
  if (success) {
    console.log("加载的记录数据:", success);

    // 如果有 note 数据，尝试解析并加载到 store
    if (success.note) {
      try {
        const noteData = JSON.parse(success.note);
        console.log("解析的 note 数据:", JSON.parse(success.note));

        // 转换为扁平化的表单数据
        const formData = medicalRecordStore.noteToFormData(noteData);

        // 设置基本信息
        formData.id = success.id || "";
        formData.name = success.name || "";
        formData.idNumber = success.idNumber || "";
        formData.recordid = success.recordid || "";

        // 初始化表单数据
        medicalRecordStore.initializeFormData(formData);
      } catch (parseError) {
        console.error("解析 note 数据失败:", parseError);
        // 如果解析失败，使用默认数据并填充基本信息
        medicalRecordStore.initializeFormData();
      }
    } else {
      // 如果没有 note 数据，使用默认数据
      medicalRecordStore.initializeFormData();
    }

    // 更新基本信息到 store
    medicalRecordStore.updateField("id", success.id || "");
    medicalRecordStore.updateField("name", success.name || "");
    medicalRecordStore.updateField("idNumber", success.idNumber || "");
    medicalRecordStore.updateField("recordid", success.recordid || "");

    // 更新其他字段到 store（如果 note 中没有的话）
    if (success.seeDate) {
      medicalRecordStore.updateField("visitTime", success.seeDate);
    }
    if (success.diagnosisResult) {
      medicalRecordStore.updateField("diagnosisResult", success.diagnosisResult);
    }
    if (success.diagnosisBasis) {
      medicalRecordStore.updateField("diagnosisBasis", success.diagnosisBasis);
    }
    if (success.hospital) {
      medicalRecordStore.updateField("hospital", success.hospital);
    }
    if (success.department) {
      medicalRecordStore.updateField("department", success.department);
    }
    if (success.dept) {
      medicalRecordStore.updateField("dept", success.dept);
    }
    if (success.project) {
      medicalRecordStore.updateField("project", success.project);
    }
    if (success.specialistAssessment) {
      medicalRecordStore.updateField("specialistAssessment", success.specialistAssessment);
    }
    if (success.surgeryName) {
      medicalRecordStore.updateField("surgeryName", success.surgeryName);
    }
    if (success.surgeryTime) {
      medicalRecordStore.updateField("surgeryTime", success.surgeryTime);
    }
    if (success.surgeryHospital) {
      medicalRecordStore.updateField("surgeryHospital", success.surgeryHospital);
    }
    if (success.medicationAllergy) {
      medicalRecordStore.updateField("medicationAllergy", success.medicationAllergy);
    }
    if (success.foodAllergy) {
      medicalRecordStore.updateField("foodAllergy", success.foodAllergy);
    }
    if (success.otherAllergy) {
      medicalRecordStore.updateField("otherAllergy", success.otherAllergy);
    }
    if (success.familyDiseaseHistory) {
      medicalRecordStore.updateField("familyHistory", success.familyDiseaseHistory);
    }
    if (success.physicalExamination) {
      medicalRecordStore.updateField("physicalExamination", success.physicalExamination);
    }
    if (success.organExamination) {
      medicalRecordStore.updateField("organExamination", success.organExamination);
    }
    if (success.auxiliaryExamination) {
      medicalRecordStore.updateField("auxiliaryExamination", success.auxiliaryExamination);
    }
    if (success.prescription) {
      medicalRecordStore.updateField("prescription", success.prescription);
    }
    if (success.disposition) {
      medicalRecordStore.updateField("disposition", success.disposition);
    }
    if (success.healthEducation) {
      medicalRecordStore.updateField("healthEducation", success.healthEducation);
    }
  }
}

/**
 * 加载记录数据
 */
async function loadRecordData(id: string) {
  try {
    console.log("开始加载记录数据，ID:", id);

    // 请求记录详情
    const { success } = await request.get<any>(
      `${PageItem.commUrl}/queryById`,
      {
        id: id,
      },
      {
        useErrMsg: true,
      }
    );

    initRecordData(success);
  } catch (error) {
    console.error("加载记录数据失败:", error);
    Taro.showToast({ title: "加载数据失败", icon: "error" });
  }
}

async function submitForm() {
  try {
    console.log("开始提交表单数据");

    // 基本验证
    if (!formData.value?.name) {
      Taro.showToast({ title: "请输入姓名", icon: "error" });
      return;
    }
    if (!formData.value?.idNumber) {
      Taro.showToast({ title: "请输入证件号码", icon: "error" });
      return;
    }

    // 构建完整的医疗记录数据
    // const medicalRecordData = buildMedicalRecordData();
    // console.log('构建的医疗记录数据:', medicalRecordData);

    // 使用 store 的保存方法
    const result = await medicalRecordStore.saveToPastMedicalInfo(recordId.value);

    if (result.success) {
      console.log("保存成功:", result);

      // 如果是新增模式，更新 recordId
      if (!recordId.value && result.data?.id) {
        recordId.value = result.data.id;
      }

      Taro.showToast({ title: "保存成功", icon: "success" });

      // 延迟返回上一页
      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    } else {
      console.error("保存失败:", result.message);
      Taro.showToast({ title: result.message || "保存失败", icon: "error" });
    }
  } catch (error) {
    console.error("保存失败:", error);
    Taro.showToast({ title: "保存失败", icon: "error" });
  }
}

function goBack() {
  console.log("goBack")
  const params = new URLSearchParams(window.location.search);
  const pinggu = params.get("pinggu");
  if(pinggu){
    Taro.navigateBack();
  }
  else{
    history.back()
  }
}

async function changeHealthAssessmentStatus(orderId: String, isMedicalOrder: number) {
  console.log('转为入户工单，id = ' + orderId);
  // return request.get<any>(
  //   `/nurse_user_orders/nurseUserOrders/changeHealthAssessmentStatus?orderId=${orderId}&isMedicalOrder=${isMedicalOrder}`,
  //   {},
  //   {
  //     useErrMsg: true
  //   }
  // );
  // 给小程序的webview发送消息
  if(window.wx){
    wx.miniProgram.postMessage({
      data: {
        type: 'goToOrder'
      }
    });
    wx.miniProgram.navigateBack();
  }

}
/**
 * 跳转到居家护理专项评估页面
 */
function goToHomeCareAssessment() {
  try {
    console.log("跳转到居家护理专项评估页面");

    // 构建跳转参数
    const params = new URLSearchParams();
    params.append("type", "homeCareAssessment");

    if (form.idNumber) {
      params.append("idNumber", form.idNumber);
    }
    if (form.name) {
      params.append("name", form.name);
    }

    // 跳转到居家护理专项评估页面
    const url = `/pages/home-care-assessment/index?${params.toString()}`;
    console.log("跳转URL:", url);
    
    Taro.navigateTo({
      url: url,
      success: () => {
        console.log("居家护理专项评估页面跳转成功");
      },
      fail: (error) => {
        console.error("居家护理专项评估页面跳转失败:", error);
        Taro.showToast({
          title: "页面跳转失败",
          icon: "none",
          duration: 2000,
        });
      }
    });
  } catch (error) {
    console.error("跳转到居家护理专项评估页面时出错:", error);
    Taro.showToast({
      title: "跳转失败",
      icon: "none",
      duration: 2000,
    });
  }
}

/**
 * 跳转到全面健康评估页面
 */
function goToHealthAssessment() {
  try {
    console.log("跳转到全面健康评估页面");

    // 构建跳转参数
    const params = new URLSearchParams();
    params.append("type", "allCareAssessment");

    if (form.idNumber) {
      params.append("idNumber", form.idNumber);
    }
    
    // 传递记录ID，确保 sub-form 页面能正确加载数据
    if (formData.value.id) {
      params.append("id", formData.value.id);
    }

    const url = `/pages/medical-record/sub-form?${params.toString()}`;
    console.log("跳转URL:", url);

    Taro.navigateTo({
      url: url,
    });
  } catch (error) {
    console.error("跳转失败:", error);
    Taro.showToast({
      title: "跳转失败",
      icon: "error",
    });
  }
}

/**
 * 健康需求属性优化评估相关函数
 */

// 更新健康属性占比
function updateHealthAttributeProportion(attributeType: string, value: string) {
  const proportion = parseInt(value) || 0;
  
  if (!formData.value.healthDemandAttributeOptimization) {
    formData.value.healthDemandAttributeOptimization = {
      medicalAttribute: { proportion: 0, description: '', images: [] },
      healthAttribute: { proportion: 0, description: '', images: [] },
      rehabilitationAttribute: { proportion: 0, description: '', images: [] },
      careAttribute: { proportion: 0, description: '', images: [] },
      additionalAttributes: [],
      historicalAssessments: []
    };
  }
  
  const attr = formData.value.healthDemandAttributeOptimization[attributeType];
  if (attr && typeof attr === 'object' && 'proportion' in attr) {
    (attr as any).proportion = proportion;
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 更新健康属性数据（描述和图片）
function updateHealthAttributeData(attributeType: string, data: any) {
  if (!formData.value.healthDemandAttributeOptimization) {
    formData.value.healthDemandAttributeOptimization = {
      medicalAttribute: { proportion: 0, description: '', images: [] },
      healthAttribute: { proportion: 0, description: '', images: [] },
      rehabilitationAttribute: { proportion: 0, description: '', images: [] },
      careAttribute: { proportion: 0, description: '', images: [] },
      additionalAttributes: [],
      historicalAssessments: []
    };
  }
  
  const attr = formData.value.healthDemandAttributeOptimization[attributeType];
  if (attr && typeof attr === 'object' && 'description' in attr && 'images' in attr) {
    (attr as any).description = data.description || '';
    (attr as any).images = data.images || [];
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 添加额外属性
function addAdditionalAttribute() {
  if (!formData.value.healthDemandAttributeOptimization) {
    formData.value.healthDemandAttributeOptimization = {
      medicalAttribute: { proportion: 0, description: '', images: [] },
      healthAttribute: { proportion: 0, description: '', images: [] },
      rehabilitationAttribute: { proportion: 0, description: '', images: [] },
      careAttribute: { proportion: 0, description: '', images: [] },
      additionalAttributes: [],
      historicalAssessments: []
    };
  }
  
  if (!formData.value.healthDemandAttributeOptimization.additionalAttributes) {
    formData.value.healthDemandAttributeOptimization.additionalAttributes = [];
  }
  
  formData.value.healthDemandAttributeOptimization.additionalAttributes.push({
    name: '',
    proportion: 0,
    description: '',
    images: []
  });
  
  medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
}

// 更新额外属性名称
function updateAdditionalAttributeName(index: number, value: string) {
  if (formData.value.healthDemandAttributeOptimization?.additionalAttributes?.[index]) {
    formData.value.healthDemandAttributeOptimization.additionalAttributes[index].name = value;
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 更新额外属性占比
function updateAdditionalAttributeProportion(index: number, value: string) {
  const proportion = parseInt(value) || 0;
  if (formData.value.healthDemandAttributeOptimization?.additionalAttributes?.[index]) {
    formData.value.healthDemandAttributeOptimization.additionalAttributes[index].proportion = proportion;
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 更新额外属性数据
function updateAdditionalAttributeData(index: number, data: any) {
  if (formData.value.healthDemandAttributeOptimization?.additionalAttributes?.[index]) {
    formData.value.healthDemandAttributeOptimization.additionalAttributes[index].description = data.description || '';
    formData.value.healthDemandAttributeOptimization.additionalAttributes[index].images = data.images || [];
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 删除额外属性
function removeAdditionalAttribute(index: number) {
  if (formData.value.healthDemandAttributeOptimization?.additionalAttributes) {
    formData.value.healthDemandAttributeOptimization.additionalAttributes.splice(index, 1);
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}

// 删除历史评估记录
function removeHistoricalAssessment(index: number) {
  if (formData.value.healthDemandAttributeOptimization?.historicalAssessments) {
    formData.value.healthDemandAttributeOptimization.historicalAssessments.splice(index, 1);
    medicalRecordStore.updateField('healthDemandAttributeOptimization', formData.value.healthDemandAttributeOptimization);
  }
}
</script>

<style scoped lang="scss">
:deep(.nut-textarea) {
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  background: #f0f0f0;
}

/* 健康需求属性优化评估输入框样式 */
:deep(.nut-input) {
  &.health-attribute-input {
    border-radius: 6rpx;
    padding: 4rpx 6rpx;
    background: white;
    border: 1px solid #e5e7eb;
    font-size: 18rpx;
    text-align: center;
    height: 32rpx;
    min-height: 32rpx;
    line-height: 1.2;
    
    &:focus {
      border-color: #3b82f6;
      background: #fff;
      box-shadow: 0 0 0 2rpx rgba(59, 130, 246, 0.1);
    }
  }
}

/* 额外属性输入框样式 */
:deep(.nut-input) {
  &.additional-attribute-input {
    border-radius: 4rpx;
    padding: 4rpx 6rpx;
    background: white;
    border: 1px solid #e5e7eb;
    font-size: 16rpx;
    text-align: center;
    height: 28rpx;
    min-height: 28rpx;
    line-height: 1.2;
    
    &:focus {
      border-color: #6b7280;
      background: #fff;
      box-shadow: 0 0 0 1rpx rgba(107, 114, 128, 0.1);
    }
  }
}
.btnss{
  white-space: nowrap;
}

// 折叠动画样式
.collapse-header {
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: #f0f0f0;
  }

  &:active {
    background-color: #e0e0e0;
  }
}

.collapse-content {
  overflow: hidden;
  transition: all 0.3s ease;
}

// 箭头旋转动画
.arrow-icon {
  transition: transform 0.2s ease;
}

.arrow-icon.expanded {
  transform: rotate(180deg);
}

// 确保旋转动画平滑
.rotate-0 {
  transform: rotate(0deg);
}

.rotate-180 {
  transform: rotate(180deg);
}
.btops {
  border-top: solid 6rpx #8bc34a;
}
.youhua{
  border-top: solid 6rpx #8bc34a;
  :deep(.nut-input){
    padding: 4rpx 12rpx !important;
    margin: 0 12rpx !important;
  }
}

// 日历弹窗样式
.calendar-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    position: relative;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      position: absolute;
      right: 32rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40rpx;
      color: #999;
      cursor: pointer;
      
      &:active {
        opacity: 0.6;
      }
    }
  }
  
  .calendar-content {
    flex: 1;
    overflow-y: auto;
    padding: 16rpx;
  }
  
  .popup-footer {
    display: flex;
    gap: 24rpx;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    border-top: 1rpx solid #f0f0f0;
    
    .nut-button {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
